package com.jiashihui.web.mybatis;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.junit.Test;

/**
 * @author jiashihui
 * @describe: （数据库密码）加密解密
 * @date 2019/02/13
 *
 * 在启动命令中配置JVM参数（jasypt.encryptor.password），注入加密密文的密码。
 * java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=0123456789ace -jar -Xmx512m settlement.jar
 * 在docker容器中密文的密码可以设置成环境变量（如：JASYPT_PASSWORD ）,上述命令可以修改为：
 * java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=${JASYPT_PASSWORD} -jar -Xmx512m settlement.jar
 */
public class JasyptPw {
    @Test
    public void testEncrypt() throws Exception {
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();

        // 加密的算法，这个算法是默认的
        config.setAlgorithm("PBEWithMD5AndDES");
        // 加密的密钥
        config.setPassword("0123456789ace");
        standardPBEStringEncryptor.setConfig(config);
        String plainText = "123456";
        String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
        System.out.println(encryptedText);
    }

    @Test
    public void testDe() throws Exception {
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();

        config.setAlgorithm("PBEWithMD5AndDES");
        config.setPassword("0123456789ace");
        standardPBEStringEncryptor.setConfig(config);
        String encryptedText = "mNmiOYvfIffvyxx2HcllYQ==";
        String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
        System.out.println(plainText);
    }
}
